package widget

import (
	"image/color"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
)

type BorderedContainer struct {
	content fyne.Widget // ❌ 原来是 CanvasObject，现在改为 Widget
	rect    *canvas.Rectangle
}

func NewBorderedContainer(content fyne.Widget) *BorderedContainer {
	return &BorderedContainer{
		content: content,
		rect: &canvas.Rectangle{
			FillColor:   nil,
			StrokeColor: color.RGBA{R: 255, G: 0, B: 0, A: 255}, // 红色边框
			StrokeWidth: 3,
		},
	}
}

func (c *BorderedContainer) CreateRenderer() fyne.WidgetRenderer {
	return &borderedContainerRenderer{c, c.rect, c.content.CreateRenderer()}
}

// Refresh 手动触发刷新
func (c *BorderedContainer) Refresh() {
	c.content.Refresh()
}

// MinSize 获取最小尺寸
func (c *BorderedContainer) MinSize() fyne.Size {
	return c.content.MinSize()
}

// Move 设置位置
func (c *BorderedContainer) Move(pos fyne.Position) {
	c.content.Move(pos)
}

// Position 获取位置
func (c *BorderedContainer) Position() fyne.Position {
	return c.content.Position()
}

// Resize 调整大小
func (c *BorderedContainer) Resize(size fyne.Size) {
	c.content.Resize(size)
	c.rect.Resize(size)
}

// Show 显示
func (c *BorderedContainer) Show() {
	c.content.Show()
	c.rect.Show()
}

// Hide 隐藏
func (c *BorderedContainer) Hide() {
	c.content.Hide()
	c.rect.Hide()
}

// Visible 是否可见
func (c *BorderedContainer) Visible() bool {
	return c.content.Visible()
}

// Size 获取当前尺寸
func (c *BorderedContainer) Size() fyne.Size {
	return c.content.Size()
}

// Destroy 销毁
func (c *BorderedContainer) Destroy() {}

// ----------------------------
// 渲染器部分
// ----------------------------

type borderedContainerRenderer struct {
	container *BorderedContainer
	rect      *canvas.Rectangle
	renderer  fyne.WidgetRenderer
}

func (r *borderedContainerRenderer) Layout(size fyne.Size) {
	r.renderer.Layout(size)
	r.rect.Resize(size)
}

func (r *borderedContainerRenderer) MinSize() fyne.Size {
	return r.container.MinSize()
}

func (r *borderedContainerRenderer) Refresh() {
	r.renderer.Refresh()
	r.rect.Refresh()
}

func (r *borderedContainerRenderer) Objects() []fyne.CanvasObject {
	// 创建一个新的切片，第一个元素是红色边框 rect
	// 然后用 append 把原始控件的渲染对象追加进去
	objects := append([]fyne.CanvasObject{r.rect}, r.renderer.Objects()...)
	return objects
}
func (r *borderedContainerRenderer) Destroy() {
	r.renderer.Destroy()
}
